from flask import Blueprint, render_template, request

from applications.common import curd
from applications.common.curd import model_to_dicts
from applications.common.helper import ModelFilter
from applications.common.utils.http import table_api, fail_api, success_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import xss_escape
from applications.extensions import db
from applications.models import Role, Traindata
from applications.schemas import TraindataOutSchema

admin_traindata = Blueprint('adminTraindata', __name__, url_prefix='/admin/traindata')


# 设备管理
@admin_traindata.get('/')
#@authorize("admin:user:main", log=True)
def main():
    return render_template('admin/traindata/main.html')

# 设备分页查询
@admin_traindata.get('/data')
def data():
    # 获取请求参数
    id = request.args.get('id', type=int)
    Name = xss_escape(request.args.get('Name', type=str))
    number = request.args.get('number', type=int)
    date = xss_escape(request.args.get('date', type=str))
    stime = xss_escape(request.args.get('stime', type=str))
    etime = xss_escape(request.args.get('etime', type=str))
    train = xss_escape(request.args.get('train', type=str))

    # 查询参数构造
    mf = ModelFilter()
    if id:
        mf.exact(field_name="id", value=id)
    if number:
        mf.exact(field_name="number", value=number)
    if Name:
        mf.contains(field_name="Name", value=Name)
    if date:
        mf.contains(field_name="date", value=date)
    if stime:
        mf.contains(field_name="stime", value=stime)
    if etime:
        mf.contains(field_name="etime", value=etime)
    if train:
        mf.contains(field_name="train", value=etime)
    # orm查询
    # 使用分页获取data需要.items
    traindata = Traindata.query.filter(mf.get_filter(model=Traindata)).layui_paginate()
    count = traindata.total
    # 返回api
    return table_api(data=model_to_dicts(schema=TraindataOutSchema, data=traindata.items), count=count)


# 删除设备
@admin_traindata.delete('/remove/<int:id>')
@authorize("admin:traindata:remove", log=True)
def delete(id):
    user = Traindata.query.filter_by(id=id).first()
    user.role = []

    res = Traindata.query.filter_by(id=id).delete()
    db.session.commit()
    if not res:
        return fail_api(msg="删除失败")
    return success_api(msg="删除成功")

#  编辑设备
@admin_traindata.get('/edit/<int:id>')
@authorize("admin:traindata:edit", log=True)
def edit(id):
    traindata = curd.get_one_by_id(Traindata, id)
    roles = Role.query.all()
    checked_roles = []
    for r in roles:
        checked_roles.append(r.id)
    return render_template('admin/traindata/edit.html', traindata=traindata, roles=roles, checked_roles=checked_roles)


#  编辑设备
@admin_traindata.put('/update')
@authorize("admin:traindata:edit", log=True)
def update():
    req_json = request.json
    a = req_json.get("roleIds")
    id = xss_escape(req_json.get("id"))
    Name = xss_escape(req_json.get('Name'))
    number = xss_escape(req_json.get('number'))
    date = xss_escape(req_json.get('date'))
    train = xss_escape(req_json.get('train'))
    role_ids = a.split(',')
    Traindata.query.filter_by(id=id).update({'Name': Name, 'number': number, 'date': date, 'train': train})
    u = Traindata.query.filter_by(id=id).first()

    roles = Role.query.filter(Role.id.in_(role_ids)).all()
    u.role = roles

    db.session.commit()
    return success_api(msg="更新成功")


# 批量删除
@admin_traindata.delete('/batchRemove')
@authorize("admin:traindata:remove", log=True)
def batch_remove():
    ids = request.form.getlist('ids[]')
    for id in ids:
        user = Traindata.query.filter_by(id=id).first()
        user.role = []

        res = Traindata.query.filter_by(id=id).delete()
        db.session.commit()
    return success_api(msg="批量删除成功")